package cn.edu.bjtu;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DBConnecttion {

	    public static void main(String[] args) {
	    	try {
	    	     Connection con = getConnect();
	    
	            //要执行的SQL语句
	            String sql = "select * from usertable where userno=? and password=?";
	            //2.创建statement类对象，用来执行SQL语句！！
	            PreparedStatement statement = con.prepareStatement(sql);
	            statement.setString(1, "10120496");
	            statement.setString(2, "10120496");
	            //3.ResultSet类，用来存放获取的结果集！！
	            ResultSet rs = statement.executeQuery();
	            System.out.println("-----------------");
	            System.out.println("执行结果如下所示:");  
	            System.out.println("-----------------");  
	            System.out.println("姓名" + "\t" + "职称");  
	            System.out.println("-----------------");  
	            String UserNo = null;
	            String Passowrd = null;
	            if(rs.next()){
	               /* //获取stuname这列数据
	            	UserNo = rs.getString("userno");
	                //获取stuid这列数据
	            	Passowrd = rs.getString("password");*/

	                //输出结果
	                System.out.println("登陆成功");
	            }else{
	            	  System.out.println("登陆失败");
	            }
	            rs.close();
	            con.close();
	    	}catch (Exception e) {
				// TODO: handle exception
			}
	    }
	    public static Connection getConnect() {
	    	//声明Connection对象
	        Connection con = null;
	        //驱动程序名
	        String driver = "com.mysql.jdbc.Driver";
	        //URL指向要访问的数据库名mydata
	        String url = "jdbc:mysql://localhost:3306/literaturesystem";
	        //MySQL配置时的用户名
	        String user = "zzd";
	        //MySQL配置时的密码
	        String password = "zw156323";
	        //遍历查询结果集
	        try {
	            //加载驱动程序
	            Class.forName(driver);
	            //1.getConnection()方法，连接MySQL数据库！！
	            con = DriverManager.getConnection(url,user,password);
	            if(!con.isClosed())
	                System.out.println("Succeeded connecting to the Database!");
	            return con;
	        }catch (Exception e) {
				// TODO: handle exception
			}
			return con;
	    }
	}
